package com.ideabove.radio.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ideabove.adapter.CommentAdapter;
import com.ideabove.data.Comment;
import com.ideabove.data.PlayItem;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.module.FacebookMd;
import com.ideabove.util.LogUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.widget.ListAdapter;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class PlayBackService extends Service 
{
	
	public static boolean isRunningApp = true;

	public static class MediaPlayerSingleton
	{    			
		static MediaPlayer mMediaPlayer = null;
		public static String whatKindOfNetwork = "3g";
		public static int percent = 0;

		// banner
		public static int BANNER_SHOW_DELAY_TIME = 1000 * 60 * 10;
		public static boolean itsbannertime = true;
		public static int genreScrollViewHeight = 0;
		public static int playerScrollViewHeight = 0;

		public static int videoWrapWidth = 0;
		public static int videoWrapHeight = 0;

		public static int playMode = 2;		
		public static int PLAY_MODE_ONE_REPEAT = 1;
		public static int PLAY_MODE_REPEAT = 2;


		public static MediaPlayer getInstance(){		
			//			Log.e("getInstance", "MediaPlayerSingleton"+ mMediaPlayer);
//			mMediaPlayer.setOnErrorListener(new OnErrorListener() {
//				
//				@Override
//				public boolean onError(MediaPlayer mp, int what, int extra) {
//					// TODO Auto-generated method stub
//					return false;
//				}
//			});
			return mMediaPlayer;
		}
		public static void remove(){
			//			Log.e("remove", "MediaPlayerSingleton");
			if(mMediaPlayer != null){
				mMediaPlayer.reset();
				mMediaPlayer.release();
				mMediaPlayer = null;
			}
		}		
		public static void reset(){
			//			Log.e("reset", "MediaPlayerSingleton");
			percent = 0;
			if(mMediaPlayer != null){
				mMediaPlayer.reset();
				mMediaPlayer.release();
			}			
			mMediaPlayer = new MediaPlayer();						
		}		

		public static int getDPI(int size, DisplayMetrics metrics){
			return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;        
		}
	}

	MediaPlayer mMediaPlayer;	
	public static final int REQUEST_MSG_GET_BONO_CH_PLAYLIST = 1;
	public static final int REQUEST_MSG_GET_USER_PLAYLIST = 2;
	public static final int REQUEST_MSG_GET_VIDEO_TO_PLAY = 3;	
	public static final int REQUEST_MSG_GET_TEMP_VIDEO_TO_PLAY = 4;
	
	public static final int REQUEST_MSG_GET_CURRENT_POSITION = 5;
	public static final int REQUEST_MSG_GET_BONO_GENRE_PLAYLIST = 6;
	public static final int REQUEST_MSG_GET_NEXT_VIDEO_TO_PLAY = 7;
	public static final int REQUEST_MSG_GET_PRE_VIDEO_TO_PLAY = 8;
	public static final int REQUEST_MSG_GET_REPEAT_VIDEO_TO_PLAY = 9;
	public static final int REQUEST_MSG_GET_VIDEO_INFO = 10;

	public static final int REQUEST_MSG_GET_ALL_FOLDER_TO_PLAY = 11;
	public static final int REQUEST_MSG_FOCUS_PLAYITEM_TO_PLAY = 12;
	public static final int REQUEST_MSG_ADD_TEMP_PLAYITEM_PLAY = 13;
	public static final int REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY = 14;
	public static final int REQUEST_DONE_GET_KAKAO_VIDEO_TO_PLAY = 15;

	public static final int REQUEST_DONE_BONO_PLAYLIST = 21;
	public static final int REQUEST_DONE_GET_VIDEO_TO_PLAY = 22;
	public static final int REQUEST_DONE_GET_VIDEO_INFO = 23;
	public static final int REQUEST_DONE_GET_NEXT_VIDEO_TO_PLAY = 24;
	public static final int REQUEST_DONE_MSG_GET_CURRENT_POSITION = 25;
	public static final int REQUEST_DONE_MSG_GET_BONO_GENRE_PLAYLIST = 26;
		
	
	public static final int SETTING_PLAYBACK_MODE = 30;	
	
	public static final int NOTICE_ERROR_NOT_AVAILABLE_VIDEO = 100;
	
	
	public static int displayMode = 0;
	public static final int PLAY_FROEGRUND = 101;
	public static final int PLAY_REAL_BACKGROUND = 102;
	public static final int PLAY_PHONE_BACKGROUND = 103;

	final Messenger mMessenger = new Messenger(new IncomingHandler());
	Messenger mClient = null;

	HttpClient httpPlayerClient = null;

	@Override
	public IBinder onBind(Intent intent) {
		//    	Log.e("onBind", "onBind");

		TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		tManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);		
		
		return mMessenger.getBinder();
	}

	private PhoneStateListener phoneStateListener = new PhoneStateListener()
	{
		public void onCallStateChanged(int state, String incomingNumber) {// 전화 수신 반응.


			MediaPlayer player = MediaPlayerSingleton.getInstance();

			// 착신 전화 번호를 받는다.
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE : // 전화 안함    	  
								
				// 진짜 백그라운드 모드일때만 스타트를 시작한다.
				if(player != null && !player.isPlaying() && displayMode == PLAY_REAL_BACKGROUND){
					player.start();
				}
				break;
			case TelephonyManager.CALL_STATE_RINGING : // 전화함    	  
				if(player != null && player.isPlaying()){
					
					// 그전에 백그라운드 모드가 아니라면 잠시 전화 왔을때 백그라운드 모드가 되는것...
					if(displayMode != PLAY_REAL_BACKGROUND && displayMode == PLAY_FROEGRUND){
						displayMode = PLAY_PHONE_BACKGROUND;
					}
					
					player.pause();
				}    	  
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK :
				if(player != null && player.isPlaying()){
					player.pause();
				}
				break;

			default:      
				break;
			}
		}
	};

	//===========================================================================================================
	//		Message Stuff    
	//===========================================================================================================     
	private OnCompletionListener mOnCompletionListener  = new OnCompletionListener() {		
		@Override
		public void onCompletion(MediaPlayer mp) {

			try{
				//				Log.e("OnCompletionListener", "OnCompletionListener Background");
				String ytNextLink = getNextPlayItem().getLink();
				getYtUrlOnBackground(ytNextLink);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	private MediaPlayer.OnErrorListener mErrorListener =
		new MediaPlayer.OnErrorListener() {
		public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
			//    		Log.e("OnErrorListener", "Error: " + framework_err + "," + impl_err);
			//    		Toast.makeText(getApplicationContext(), "play", Toast.LENGTH_LONG).show();
			MediaPlayerSingleton.remove();
			return true;
		}
	};

	@SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			MediaPlayerSingleton.percent = 1000;
			switch (msg.what) {
			case REQUEST_MSG_GET_BONO_CH_PLAYLIST:
				mClient = msg.replyTo;
				int channelType = msg.arg1;
				getRadioChannelData(channelType);
				break;
			case REQUEST_MSG_GET_USER_PLAYLIST:
				mClient = msg.replyTo;
				if(getCurrentPlayItem() != null){
					String uid = getCurrentPlayItem().getCpost_id();
					getRadioUserPlaylistData(uid);
				}
				break;
			case REQUEST_MSG_GET_BONO_GENRE_PLAYLIST:
				mClient = msg.replyTo;
				int genreType = msg.arg1;
				getRadioGenreData(genreType);
				break;    

			case REQUEST_MSG_ADD_TEMP_PLAYITEM_PLAY:
				mClient = msg.replyTo;
				PlayItem playItem = (PlayItem)msg.obj;
				getTempYtUrlAndNotice(playItem);			
				break;

			case REQUEST_MSG_FOCUS_PLAYITEM_TO_PLAY:
				mClient = msg.replyTo;

				clearPlayList();
				HashMap<String, Object> dataToSend = (HashMap<String, Object>) msg.obj;

				playList = (ArrayList<PlayItem>)dataToSend.get("array");            	
				String link =  (String)dataToSend.get("link");				 
				focusPlayItemToPlay(link);

				
				sendMessageToUI(PlayBackService.REQUEST_DONE_BONO_PLAYLIST);
				break;

			case REQUEST_MSG_GET_VIDEO_TO_PLAY:
				mClient = msg.replyTo;				
				if(getCurrentPlayItem() != null){
					String ytLink = getCurrentPlayItem().getLink();
					getYtUrlAndNotice(ytLink,1); //next
				}            	
				break;
			case REQUEST_MSG_GET_TEMP_VIDEO_TO_PLAY:
				mClient = msg.replyTo;
				PlayItem playItemKakao = (PlayItem)msg.obj;
				getYtFromKakaoAndNotice(playItemKakao, 1);
				break;
				
			case REQUEST_MSG_GET_PRE_VIDEO_TO_PLAY:
				mClient = msg.replyTo;
				if(getPrePlayItem() != null){
					String ytPreLink = getCurrentPlayItem().getLink();
					getYtUrlAndNotice(ytPreLink,2); // pre
				}
				break;
			case REQUEST_MSG_GET_VIDEO_INFO:
				mClient = msg.replyTo;
				if(getCurrentPlayItem() != null){
					String ytPreLink = getCurrentPlayItem().getLink();
					getVideoInfoAndNotice(ytPreLink,1);
				}
				break;
				
			case REQUEST_MSG_GET_REPEAT_VIDEO_TO_PLAY:
				mClient = msg.replyTo;
				if(getCurrentPlayItem() != null){
					String ytCurLink = getCurrentPlayItem().getLink();
					getYtUrlAndNotice(ytCurLink,1); // next
				}
				break;

			case REQUEST_MSG_GET_NEXT_VIDEO_TO_PLAY:
				
				mClient = msg.replyTo;

				if(getNextPlayItem() != null){
					String ytNextLink = getCurrentPlayItem().getLink();
					getYtUrlAndNotice(ytNextLink,1); // pre
				}

				break;            	

			case SETTING_PLAYBACK_MODE:            	
				mMediaPlayer = (MediaPlayer)MediaPlayerSingleton.getInstance();

				if(mMediaPlayer != null){
					
					// 전화가 걸려와서 백으로 돌아간게 아니라 오직 사용자에 의해서 백모드로 간거라면...
					
					if(displayMode == PLAY_FROEGRUND){
						displayMode = PLAY_REAL_BACKGROUND;
					}
					mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
					mMediaPlayer.setOnErrorListener(mErrorListener);
				}            	 
				break;
			case REQUEST_MSG_GET_CURRENT_POSITION:
				MediaPlayer mediaPlayer = MediaPlayerSingleton.getInstance();
				if(mediaPlayer != null && mediaPlayer.isPlaying()){
					sendMessageToUI(REQUEST_DONE_MSG_GET_CURRENT_POSITION,
							getCurrentPlayItem(),mediaPlayer.getCurrentPosition());
				}
				break;

			case REQUEST_MSG_GET_ALL_FOLDER_TO_PLAY:
				mClient = msg.replyTo;
				clearPlayList();
				playList = (ArrayList<PlayItem>)msg.obj;
				sendMessageToUI(PlayBackService.REQUEST_DONE_BONO_PLAYLIST);
				break;
				
			case NOTICE_ERROR_NOT_AVAILABLE_VIDEO:
				try{
					PlayItem pItem = (PlayItem)msg.obj;				
					Toast toast = Toast.makeText(getApplicationContext(),pItem.getTitle() + "은(는) \n모바일에서 재생할 수 없는 영상입니다.\n" +
					 		" http://www.bonosound.com 이용해 주세요", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, -100);
					toast.show();
				}catch(Exception e){
					e.printStackTrace();
				}
				 
				break;

			default:
				super.handleMessage(msg);
			}
		}
	}
	private void sendMessageToUI(int msgType) {
		try {
			// Send data as an Integer    		 
			mClient.send(Message.obtain(null, msgType, 0, 0));
		} catch (RemoteException e) {
			mClient = null;
		}
	}

	private void sendMessageToUI(int msgType, Object obj) {
		try {
			Message msg = Message.obtain(null, msgType);
			msg.obj = obj;
			//            msg.setData(bundle);
			mClient.send(msg);
		} catch (RemoteException e) {
			mClient = null;
		}
	}

	private void sendMessageToUI(int msgType, Object obj, int arg1) {
		try {
			Message msg = Message.obtain(null, msgType);
			msg.obj = obj;
			msg.arg1 = arg1;
			//               msg.setData(bundle);
			mClient.send(msg);
		} catch (RemoteException e) {
			mClient = null;
		}
	}


	//================================================================================================
	// 		ytNewWork Stuff..........    
	//================================================================================================    

	Thread m_GetDataThread = null;
	Thread m_PlayThread = null;	
	Thread m_CommentThread = null;
	PlayItem m_currentPlayVideo = null;

	private ArrayList<PlayItem> playList = new ArrayList<PlayItem>();
	public int currentIdx = 0;

	private PlayItem getCurrentPlayItem(){
		
		if(playList != null && playList.size() > 0){
			return playList.get(currentIdx);
		}
		return null;		
	}

	private PlayItem getPlayItemFromLink(String link) throws Exception{
		PlayItem tempItem = null;

		int i = 0;
		for(i = 0; i < playList.size(); i++ ){
			tempItem = playList.get(i);
			if(link.equals(tempItem.getLink())){
				break;
			}
		}

		currentIdx = i;
		return tempItem;
	}

	private PlayItem focusPlayItemToPlay(String link){
		try {
			return getPlayItemFromLink(link);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private PlayItem getNextPlayItem(){

		if(playList == null || playList.size() == 0){
			return null;
		}
		int tempIdx =  currentIdx + 1 >= playList.size() ? 0 : ++currentIdx;
		
		if(tempIdx == 0){
			currentIdx = 0;
		}
		return playList.get(tempIdx);
	}

	private PlayItem getPrePlayItem(){

		if(playList == null || playList.size() == 0){
			return null;
		}

		int tempIdx =  currentIdx - 1 < 0 ? playList.size() - 1 : --currentIdx;		
		currentIdx = tempIdx;

		return playList.get(tempIdx);
	}

	private void clearPlayList(){
		currentIdx = 0;
		if(playList != null){
			playList.clear();
		}

	}

	private void getRadioUserPlaylistData(final String cpostId){
		if(m_GetDataThread != null ){
			return;
		}

		m_GetDataThread = new Thread(new Runnable() {
			public void run() {
				try {				
					HttpResponse response = null;
					HttpClient client = getHttpConnection();        
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 2000);
					HttpGet request = new HttpGet("http://14.63.217.155/radio_bonosound/usersongs.php?c_cid="+ cpostId);		         
					response = client.execute(request);

					String jsonStr = "";
					InputStream in = response.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					jsonStr = str.toString();					
					JSONObject jsonObj = new JSONObject(jsonStr);  
					JSONArray resultArray = jsonObj.getJSONArray("result");


					if(resultArray.length() > 0){
						clearPlayList();
					}

					for (int i = 0; i < resultArray.length(); i++) { 
						PlayItem pitem = new PlayItem();

						pitem.setCpost_id(resultArray.getJSONObject(i).getString("cpost_id").toString());
						//						pitem.setFirst_name(resultArray.getJSONObject(i).getString("first_name").toString());
						//						pitem.setLast_name(resultArray.getJSONObject(i).getString("last_name").toString());
						pitem.setTitle(resultArray.getJSONObject(i).getString("title").toString());
						pitem.setAuthor(resultArray.getJSONObject(i).getString("author").toString());
						pitem.setLink(resultArray.getJSONObject(i).getString("link").toString());
						pitem.setDuration(resultArray.getJSONObject(i).getString("duration").toString());
						pitem.setPost(resultArray.getJSONObject(i).getString("post").toString());
						pitem.setLikeCnt(resultArray.getJSONObject(i).getString("likeCnt").toString());
						playList.add(pitem);
					}

					sendMessageToUI(PlayBackService.REQUEST_DONE_BONO_PLAYLIST);
				}catch(Exception e){
					e.printStackTrace();
					Message myMessage=new Message();
					myMessage.obj="Network is not available.Try again";
					handler.sendMessage(myMessage);		
				}
				m_GetDataThread = null;	
			}
		});

		m_GetDataThread.start();
	}

	private void getRadioChannelData(final int type){
		if(m_GetDataThread != null ){
			return;
		}

		m_GetDataThread = new Thread(new Runnable() {
			public void run() {
				try {				

					HttpResponse response = null;
					HttpClient client = getHttpConnection();        
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 2000);
					HttpGet request = new HttpGet("http://14.63.217.155/radio_bonosound/channels.php?c_type="+ type);		         
					response = client.execute(request);

					String jsonStr = "";
					InputStream in = response.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					jsonStr = str.toString();					
					JSONObject jsonObj = new JSONObject(jsonStr);  
					JSONArray resultArray = jsonObj.getJSONArray("result");


					if(resultArray.length() > 0){
						clearPlayList();
					}
					
					

					for (int i = 0; i < resultArray.length(); i++) { 
						PlayItem pitem = new PlayItem();

						pitem.setCpost_id(resultArray.getJSONObject(i).getString("cpost_id").toString());
						//						pitem.setFirst_name(resultArray.getJSONObject(i).getString("first_name").toString());
						//						pitem.setLast_name(resultArray.getJSONObject(i).getString("last_name").toString());
						pitem.setTitle(resultArray.getJSONObject(i).getString("title").toString());
						pitem.setAuthor(resultArray.getJSONObject(i).getString("author").toString());
						pitem.setLink(resultArray.getJSONObject(i).getString("link").toString());
						pitem.setDuration(resultArray.getJSONObject(i).getString("duration").toString());
						pitem.setPost(resultArray.getJSONObject(i).getString("post").toString());
						pitem.setLikeCnt(resultArray.getJSONObject(i).getString("likeCnt").toString());
						playList.add(pitem);
						
					}

					sendMessageToUI(PlayBackService.REQUEST_DONE_BONO_PLAYLIST);
				}catch(Exception e){
					e.printStackTrace();
					Message myMessage=new Message();
					myMessage.obj="Network is not available.Try again";
					handler.sendMessage(myMessage);		
				}
				m_GetDataThread = null;	
			}
		});

		m_GetDataThread.start();
	}


	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_LONG).show();
		}
	};

	private HttpClient getHttpConnection(){
		System.setProperty("http.keepAlive", "false");
		HttpClient client = new DefaultHttpClient();
		return client;
	}


	private void getRadioGenreData(final int type){
		if(m_GetDataThread != null ){
			return;
		}

		m_GetDataThread = new Thread(new Runnable() {
			public void run() {
				try {
					HttpResponse response = null;
					HttpClient client = getHttpConnection();        
					HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
					HttpGet request = new HttpGet("http://14.63.217.155/radio_bonosound/genres.php?g_type="+ type);		         
					response = client.execute(request);
					

					String jsonStr = "";
					InputStream in = response.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder str = new StringBuilder();
					String line = null;
					while((line = reader.readLine()) != null)
					{					
						str.append(line);
					}
					in.close();					
					jsonStr = str.toString();					
					JSONObject jsonObj = new JSONObject(jsonStr);  
					JSONArray resultArray = jsonObj.getJSONArray("result");


					if(resultArray.length() > 0){
						clearPlayList();
					}

					for (int i = 0; i < resultArray.length(); i++) { 
						PlayItem pitem = new PlayItem();

						pitem.setCpost_id(resultArray.getJSONObject(i).getString("cpost_id").toString());
						//						pitem.setFirst_name(resultArray.getJSONObject(i).getString("first_name").toString());
						//						pitem.setLast_name(resultArray.getJSONObject(i).getString("last_name").toString());
						pitem.setTitle(resultArray.getJSONObject(i).getString("title").toString());
						pitem.setAuthor(resultArray.getJSONObject(i).getString("author").toString());
						pitem.setLink(resultArray.getJSONObject(i).getString("link").toString());
						pitem.setDuration(resultArray.getJSONObject(i).getString("duration").toString());
						pitem.setPost(resultArray.getJSONObject(i).getString("post").toString());
						pitem.setLikeCnt(resultArray.getJSONObject(i).getString("likeCnt").toString());
						playList.add(pitem);
					}

					sendMessageToUI(PlayBackService.REQUEST_DONE_BONO_PLAYLIST);
				}catch(Exception e){
					e.printStackTrace();
					Message myMessage=new Message();
					myMessage.obj="Network is not available.Try again";
					handler.sendMessage(myMessage);					
				}
				m_GetDataThread = null;	
			}
		});

		m_GetDataThread.start();
	}


	private void getYtUrlOnBackground(final String ytlink) {
		if(m_PlayThread != null){
			return;
		}
		m_PlayThread = new Thread(new Runnable() {
			public void run() {
				try {					
					PlayItem playItem = getYtUrl(ytlink);

					if(playItem != null){
						MediaPlayerSingleton.reset();
						mMediaPlayer = (MediaPlayer)MediaPlayerSingleton.getInstance();

						if("3g".equals(MediaPlayerSingleton.whatKindOfNetwork)){
							mMediaPlayer.setDataSource(playItem.getLowQualityUrl());
						}else{
							mMediaPlayer.setDataSource(playItem.getLowQualityUrl());
						}					
						mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
						mMediaPlayer.setOnErrorListener(mErrorListener); 
						mMediaPlayer.prepare();
						mMediaPlayer.start();
						
						
						
						MediaPlayerSingleton.playMode = REQUEST_DONE_GET_VIDEO_TO_PLAY;
					}
				} catch (Exception e){
					m_PlayThread = null;
					//					Log.e("connect ERROR1#######", "#####"  + ytlink);
					String ytNextLink = getNextPlayItem().getLink();
					getYtUrlOnBackground(ytNextLink);					
				}
				m_PlayThread = null;
			}			
		});
		m_PlayThread.start();			
	}

	// 임시 플레이32
	private void getTempYtUrlAndNotice(final PlayItem pItem) {
		if(m_PlayThread != null){
			m_PlayThread.interrupt();
			return;
		}

		m_PlayThread = new Thread(new Runnable() {
			public void run() {
				try {
					PlayItem playItem = getTempYtUrl(pItem);
					MediaPlayerSingleton.reset();
					sendMessageToUI(REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY, playItem);
				}catch(InterruptedException ite){
					ite.printStackTrace();
					m_PlayThread = null;
					return;
				}catch (Exception e){
					
					PlayItem playItem = null;
					MediaPlayerSingleton.reset();
					sendMessageToUI(REQUEST_DONE_GET_TEMP_VIDEO_TO_PLAY, playItem);
					
					m_PlayThread = null;
					e.printStackTrace();										
				}
				m_PlayThread = null;
			}			
		});
		m_PlayThread.setPriority(Thread.MAX_PRIORITY);
		try {
			m_PlayThread.join(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		m_PlayThread.start();			
	}

	public synchronized PlayItem getTempYtUrl(PlayItem playItem) throws Exception{

		if(httpPlayerClient != null){
			httpPlayerClient.getConnectionManager().shutdown();
		}		

		HttpResponse response = null;
		httpPlayerClient = new DefaultHttpClient();        
		HttpConnectionParams.setConnectionTimeout(httpPlayerClient.getParams(), 3000);
		HttpGet request = new HttpGet("http://youtube.com/watch?v=" + playItem.getLink());		

		//			Log.e("connect START#######", "#####" + request.getURI().toURL());
		request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");		         
		response = httpPlayerClient.execute(request);

		String jsonStr = "";
		InputStream in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		boolean ttt = false;

		//			Log.e("connect PARSE START#######", "#####" + request.getURI().toURL());
		while((line = reader.readLine()) != null)
		{	
			String s = null;				
			s = StringEscapeUtils.unescapeJava(line);
			if(line.contains("ls.setItem('PIGGYBACK_DATA', \")]}")){
				ttt = true;
			}
			if(ttt){
				str.append(s);
			}
		}
		in.close();					
		jsonStr = str.toString();

		//			LogUtils.splitAndLog("jsonStr", jsonStr);

		jsonStr = jsonStr.substring(jsonStr.indexOf("{\""), jsonStr.indexOf("\");"));

		JSONObject jsonObj = new JSONObject(jsonStr);  
		JSONObject contentObj = jsonObj.getJSONObject("content");  
		JSONObject videoObj = contentObj.getJSONObject("video"); 
		JSONArray fmtStreamMapArr = videoObj.getJSONArray("fmt_stream_map");  

		playItem.setLowQualityUrl(fmtStreamMapArr.getJSONObject(fmtStreamMapArr.length() - 1).getString("url").toString());
		playItem.setHighQualityUrl(fmtStreamMapArr.getJSONObject(0).getString("url").toString());
		
		return playItem;		
	}
	
	// type(1: next, 2:pre)
	private void getYtFromKakaoAndNotice(final PlayItem pItem, final int type) {

		new Thread(new Runnable() {
			public void run() {
				PlayItem playItem  = null;
				
				try {					
					playItem = getYtUrl(pItem);

					if(playItem == null){
						throw new NullPointerException();
					}
					getPlayItemInfo(playItem);
					getPlayCommentData(playItem);
					MediaPlayerSingleton.reset();
					sendMessageToUI(REQUEST_DONE_GET_KAKAO_VIDEO_TO_PLAY, playItem);

				}catch (Exception e){
									
					
					try {
						Message msg = Message.obtain(null, PlayBackService.NOTICE_ERROR_NOT_AVAILABLE_VIDEO);
						msg.obj = playItem;
						mMessenger.send(msg);
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
					//					Log.e("connect ERROR1#######", ytlink + "#####"  + e.getMessage());
					e.printStackTrace();
					

				}
			}			
		}).start();			
	}

	Thread ytThread =  null;

	// type(1: next, 2:pre)
	private synchronized void getYtUrlAndNotice(final String ytlink, final int type) {
//		if(m_PlayThread != null){
//			m_PlayThread.interrupt();
//			return;
//		}

		if(ytThread == null){
		
			ytThread = new Thread(new Runnable() {
				public void run() {
					PlayItem playItem = null;
					try {
											
						playItem = getYtUrl(ytlink);
	
						if(playItem == null){
							return;
						}
						getPlayItemInfo(playItem);
						getPlayCommentData(playItem);
						MediaPlayerSingleton.reset();
						sendMessageToUI(REQUEST_DONE_GET_VIDEO_TO_PLAY, playItem);
						ytThread = null;
						
					}catch (Exception e){
					
						ytThread = null;
						e.printStackTrace();
						
						try {
							Thread.sleep(100);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
							
						if(type == 2){
							String ytPreLink = getPrePlayItem().getLink();
							getYtUrlAndNotice(ytPreLink, 2);
						}else{
							String ytNextLink = getNextPlayItem().getLink();
							getYtUrlAndNotice(ytNextLink, 1);
						}
					}
				}			
			});
			
			ytThread.start();
		}
	}
	
	private void getVideoInfoAndNotice(final String ytlink, final int type) {
		if(m_PlayThread != null){
			m_PlayThread.interrupt();
			return;
		}

		m_PlayThread = new Thread(new Runnable() {
			public void run() {
				try {					
					PlayItem playItem = getYtUrl(ytlink);

					if(playItem == null){
						throw new NullPointerException();
					}
					getPlayItemInfo(playItem);
					getPlayCommentData(playItem);
					sendMessageToUI(REQUEST_DONE_GET_VIDEO_INFO, playItem);
					

				}catch(InterruptedException ite){
					//					Log.e("InterruptedException#######", "#####"  + ite);
					ite.printStackTrace();
					m_PlayThread = null;
					return;
				}catch (Exception e){
					m_PlayThread = null;
					//					Log.e("connect ERROR1#######", ytlink + "#####"  + e.getMessage());
					e.printStackTrace();
					if(type == 2){
						String ytPreLink = getPrePlayItem().getLink();
						getVideoInfoAndNotice(ytPreLink, 2);
					}else{
						String ytNextLink = getNextPlayItem().getLink();
						getVideoInfoAndNotice(ytNextLink, 1);
					}

				}
				m_PlayThread = null;
			}			
		});
		m_PlayThread.start();			
	}
	

	//
	public synchronized PlayItem getYtUrl(String ytlink) throws Exception{

		if(httpPlayerClient != null){
			httpPlayerClient.getConnectionManager().shutdown();
		}		


		HttpResponse response = null;
		httpPlayerClient = new DefaultHttpClient();        
		HttpConnectionParams.setConnectionTimeout(httpPlayerClient.getParams(), 2000);
		HttpGet request = new HttpGet("http://youtube.com/watch?v=" + ytlink);		

		Log.e("connect START#######", "#####" + request.getURI().toURL());
		request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
		
		try{
			response = httpPlayerClient.execute(request);
		}catch(Exception e){
			Thread.sleep(100);
			response = httpPlayerClient.execute(request);
		}

		String jsonStr = "";
		InputStream in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		boolean ttt = false;

		//			Log.e("connect PARSE START#######", "#####" + request.getURI().toURL());
		while((line = reader.readLine()) != null)
		{	
			String s = null;				
			s = StringEscapeUtils.unescapeJava(line);
			if(line.contains("ls.setItem('PIGGYBACK_DATA', \")]}")){
				ttt = true;
			}
			if(ttt){
				str.append(s);
			}
		}
		in.close();					
		jsonStr = str.toString();

		//			LogUtils.splitAndLog("jsonStr", jsonStr);
		
		PlayItem playItem = getPlayItemFromLink(ytlink);
		
		try{
			
			if(jsonStr.indexOf("{\"") < 0){
				if(!isRunningApp){
					return null;
				}
				
				throw new JSONException("empty");
			}
			jsonStr = jsonStr.substring(jsonStr.indexOf("{\""), jsonStr.indexOf("\");"));
	
			JSONObject jsonObj = new JSONObject(jsonStr);  
			JSONObject contentObj = jsonObj.getJSONObject("content");  
			JSONObject videoObj = contentObj.getJSONObject("video"); 
			JSONArray fmtStreamMapArr = videoObj.getJSONArray("fmt_stream_map");  
	
			playItem.setLowQualityUrl(fmtStreamMapArr.getJSONObject(fmtStreamMapArr.length() - 1).getString("url").toString());
			playItem.setHighQualityUrl(fmtStreamMapArr.getJSONObject(0).getString("url").toString());
		}catch(JSONException je){
			// 재생이 되지 않는 영상이란 것을 알린다...
			try {
				Message msg = Message.obtain(null, PlayBackService.NOTICE_ERROR_NOT_AVAILABLE_VIDEO);
				msg.obj = playItem;
				mMessenger.send(msg);
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			throw je;
		}
		
		
		return playItem;		
	}
	
	public synchronized PlayItem getYtUrl(PlayItem pItem) throws Exception{

		if(httpPlayerClient != null){
			httpPlayerClient.getConnectionManager().shutdown();
		}		


		HttpResponse response = null;
		httpPlayerClient = new DefaultHttpClient();        
		HttpConnectionParams.setConnectionTimeout(httpPlayerClient.getParams(), 3000);
		HttpGet request = new HttpGet("http://youtube.com/watch?v=" + pItem.getLink());		

		request.setHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");		         
		response = httpPlayerClient.execute(request);

		String jsonStr = "";
		InputStream in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		boolean ttt = false;

//		Log.e("connect PARSE START#######", "#####" + request.getURI().toURL());
		while((line = reader.readLine()) != null)
		{	
			String s = null;				
			s = StringEscapeUtils.unescapeJava(line);
			if(line.contains("ls.setItem('PIGGYBACK_DATA', \")]}")){
				ttt = true;
			}
			if(ttt){
				str.append(s);
			}
		}
		in.close();					
		jsonStr = str.toString();

		//			LogUtils.splitAndLog("jsonStr", jsonStr);
		
		PlayItem playItem = pItem;
		
		try{
			jsonStr = jsonStr.substring(jsonStr.indexOf("{\""), jsonStr.indexOf("\");"));
	
			JSONObject jsonObj = new JSONObject(jsonStr);  
			JSONObject contentObj = jsonObj.getJSONObject("content");  
			JSONObject videoObj = contentObj.getJSONObject("video"); 
			JSONArray fmtStreamMapArr = videoObj.getJSONArray("fmt_stream_map");  
	
			playItem.setLowQualityUrl(fmtStreamMapArr.getJSONObject(fmtStreamMapArr.length() - 1).getString("url").toString());
			playItem.setHighQualityUrl(fmtStreamMapArr.getJSONObject(0).getString("url").toString());
		}catch(JSONException je){
			// 재생이 되지 않는 영상이란 것을 알린다...
			try {
				Message msg = Message.obtain(null, PlayBackService.NOTICE_ERROR_NOT_AVAILABLE_VIDEO);
				msg.obj = playItem;
				mMessenger.send(msg);
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			throw je;
		}
		
		
		return playItem;		
	}
	

	// 
	private void getPlayCommentData(PlayItem item) throws Exception{

		final String cpostId = item.getCpost_id(); 
		HttpResponse response = null;
		HttpClient client = getHttpConnection();        
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 2000);
		HttpGet request = new HttpGet("http://14.63.217.155/radio_bonosound/comments.php?cpost_id="+ cpostId);

		response = client.execute(request);

		InputStream in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null)
		{					
			str.append(line);
		}
		in.close();					
		String jsonStr = str.toString();

		if(jsonStr != null && jsonStr.length() > 0){			
			try{
				JSONObject jsonObj = new JSONObject(jsonStr); 
				JSONArray resultArray = jsonObj.getJSONArray("result");
				ArrayList<Comment> commentArr = (ArrayList<Comment>)item.getComments();

				for (int i = 0; i < resultArray.length(); i++) {
					Comment cmt = new Comment();
					JSONObject commentObj = resultArray.getJSONObject(i);
					cmt.setUser_id(commentObj.getString("user_id").toString());
					cmt.setFirst_name(commentObj.getString("first_name").toString());
					cmt.setLast_name(commentObj.getString("last_name").toString());
					cmt.setComment(commentObj.getString("comment").toString());
					cmt.setInput_time(commentObj.getString("input_time").toString());

					commentArr.add(cmt);					
				}
			}catch(Exception e){
				//					e.printStackTrace();
			}
		}



		//					{"result":[
		//			           {"user_id":"11",
		//			        	   "first_name":"Lee",
		//			        	   "last_name":"Seunghaw",
		//			        	   "comment":"\ubc31\uc544\uc5f0\uc774\ub2e4 ^^ \ud6a8\ud6a8\ud6a8\ud6a8",
		//			        	   "input_time":"2012-11-12 16:30:39"},
		//			           {"user_id":"11",
		//			        		   "first_name":"Lee",
		//			        		   "last_name":"Seunghaw",
		//			        		   "comment":"\uc74c\ubc18\uc744 \ucd95\ud558\ud569\ub2c8\ub2e4~ \uc9f1~",
		//			        		   "input_time":"2012-11-12 16:30:56"}
		//			        ]}

	}


	private void getPlayItemInfo(PlayItem pitem) throws Exception{

		final String cpostId = pitem.getCpost_id(); 
		
		SharedPreferences prefs = getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE); 
		String uId = prefs.getString(FacebookMd.PREFERENCE_USER_BONO_ID, ""); 
		
		HttpClient client = NetWorkManager.getHttpConnection();    
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 2000);					

		HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/songInfo_android.php");
		//			uId : 유저 ID

		
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("cpostId", cpostId));
		params.add(new BasicNameValuePair("uId", uId));
		
		UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
		post.setEntity(ent);
		HttpResponse responsePOST = client.execute(post);  

		InputStream in = responsePOST.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder str = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null)
		{					
			str.append(line);
		}

		in.close();					
		String jsonStr = str.toString();

		if(jsonStr != null && jsonStr.length() > 0){			
			try{			
				JSONObject jsonObj = new JSONObject(jsonStr); 
				JSONArray resultArray = jsonObj.getJSONArray("result");

				for (int i = 0; i < resultArray.length(); i++) {
					pitem.setTitle(resultArray.getJSONObject(i).getString("title").toString());
					pitem.setPost(resultArray.getJSONObject(i).getString("post").toString());
					pitem.setGenre_id(resultArray.getJSONObject(i).getString("genre_id").toString());
					pitem.setGenre_name(resultArray.getJSONObject(i).getString("genre_name").toString());
					pitem.setViewCnt(resultArray.getJSONObject(i).getString("view_cnt").toString());
					pitem.setFolderId(resultArray.getJSONObject(i).getString("folder_id").toString());
					pitem.setOwnerId(resultArray.getJSONObject(i).getString("user_id").toString());
					pitem.setFirst_name(resultArray.getJSONObject(i).getString("first_name").toString());
					pitem.setLast_name(resultArray.getJSONObject(i).getString("last_name").toString());
					pitem.setIsLikeIdx(resultArray.getJSONObject(i).getString("isLikeIdx").toString());
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}		

	}


	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {


		super.onStart(intent, startId);		
	}

	@Override
	public void onDestroy() {
		//    	Log.e("######Servece", "onDestroy()");    	
		//    	new Thread(mPlayEnd).start();
		MediaPlayerSingleton.remove();
		super.onDestroy();
	}




}